import { createSlice } from '@reduxjs/toolkit';
import type { PayloadAction } from '@reduxjs/toolkit';
export interface UserInfo {
  username: string;
  id: string;
  role: string;
  loginTime: string;
}

export interface LoginResponse {
  token: string;
  user: {
    username: string;
    id: string;
    role: string;
  };
}

export interface AuthState {
  isLoggedIn: boolean;
  userInfo: UserInfo | null;
  authToken: string | null;
  userId: string | null;
  userRole: string | null;
  isLoading: boolean;
  error: string | null;
}

const initialState: AuthState = {
  isLoggedIn: false,
  userInfo: null,
  authToken: null,
  userId: null,
  userRole: null,
  isLoading: false,
  error: null,
};

const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    // 开始登录
    loginStart: (state) => {
      state.isLoading = true;
      state.error = null;
    },
    
    // 登录成功
    loginSuccess: (state, action: PayloadAction<LoginResponse>) => {
      state.isLoading = false;
      state.isLoggedIn = true;
      state.authToken = action.payload.token;
      state.userId = action.payload.user.id;
      state.userRole = action.payload.user.role;
      state.userInfo = {
        ...action.payload.user,
        loginTime: new Date().toISOString(),
      };
      state.error = null;
      
      // 同时保存到 localStorage
      localStorage.setItem('isLoggedIn', 'true');
      localStorage.setItem('authToken', action.payload.token);
      localStorage.setItem('userId', action.payload.user.id);
      localStorage.setItem('userRole', action.payload.user.role);
      localStorage.setItem('userInfo', JSON.stringify({
        ...action.payload.user,
        loginTime: new Date().toISOString(),
      }));
    },
    
    // 登录失败
    loginFailure: (state, action: PayloadAction<string>) => {
      state.isLoading = false;
      state.error = action.payload;
      state.isLoggedIn = false;
      state.userInfo = null;
      state.authToken = null;
      state.userId = null;
      state.userRole = null;
    },
    
    // 登出
    logout: (state) => {
      state.isLoggedIn = false;
      state.userInfo = null;
      state.authToken = null;
      state.userId = null;
      state.userRole = null;
      state.error = null;
      
      // 清除 localStorage
      localStorage.removeItem('isLoggedIn');
      localStorage.removeItem('authToken');
      localStorage.removeItem('userId');
      localStorage.removeItem('userRole');
      localStorage.removeItem('userInfo');
    },
    
    // 检查登录状态（从 localStorage 恢复）
    checkAuthStatus: (state) => {
      const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true';
      const authToken = localStorage.getItem('authToken');
      const userId = localStorage.getItem('userId');
      const userRole = localStorage.getItem('userRole');
      const userInfoStr = localStorage.getItem('userInfo');
      
      if (isLoggedIn && authToken && userId && userRole && userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr);
          state.isLoggedIn = true;
          state.authToken = authToken;
          state.userId = userId;
          state.userRole = userRole;
          state.userInfo = userInfo;
        } catch (error) {
          // 如果解析失败，清除所有状态
          state.isLoggedIn = false;
          state.userInfo = null;
          state.authToken = null;
          state.userId = null;
          state.userRole = null;
          localStorage.clear();
        }
      }
    },
    
    // 清除错误
    clearError: (state) => {
      state.error = null;
    },
    
    // 更新用户信息
    updateUserInfo: (state, action: PayloadAction<Partial<UserInfo>>) => {
      if (state.userInfo) {
        state.userInfo = { ...state.userInfo, ...action.payload };
        localStorage.setItem('userInfo', JSON.stringify(state.userInfo));
      }
    },
  },
});

export const {
  loginStart,
  loginSuccess,
  loginFailure,
  logout,
  checkAuthStatus,
  clearError,
  updateUserInfo,
} = authSlice.actions;

export default authSlice.reducer;